const mongoose = require("mongoose");
var Dish = mongoose.model("dish");
const request = require('request');
var webServiceProperties = require('../WebServiceProperties');
var dishesUrl = webServiceProperties.recommendDishesUrl;
var imgUrl = webServiceProperties.imgUrl;

exports.loadDishes = function (req, res) {
    if (req.query.recommend) {
        var recommend = req.query.recommend;
        if (recommend == 2) {
            //去A端拿菜的数据
            var recommendDishes = [];
            request(dishesUrl, function (error, response, body) {
                console.log(dishesUrl);
                if (!error && response.statusCode == 200) {
                    // console.log("dishes from A" + body); // Show the HTML for the Google homepage.
                    dishes = JSON.parse(body);
                    dishes.forEach(function (item, index, array) {
                        // console.log("dishes item" + item);
                        var did = item._id;
                        Dish.findOne({_id: did}, function (err, dish) {
                            if (!err && dish != null) {
                                dish.dicon = imgUrl + dish.dicon;
                                // console.log('get recommend dish success:' + dish.dicon);
                                recommendDishes.push(dish);
                            }
                            else {
                                console.log("{'get recommend dish':'Fail'}");
                            }
                            if (index == array.length - 1) {

                                recommendDishes.forEach(function(dish,inx){
                                    var index = Math.floor(Math.random()*recommendDishes.length);
                                    if(index != inx){
                                        var temp = recommendDishes[index];
                                        recommendDishes[index] = dish;
                                        recommendDishes[inx] = temp;
                                    };
                                });

                                res.json(recommendDishes);
                            }
                        });

                    });


                }
            })

        } else if (recommend == 3) {
            //查询未下架的菜单
            var mid = req.session.mid;
            if(mid){
                Dish.find({recommend: {$ne: -1}, merchant: mid}, function (err, dishes) {
                    dishes.forEach(function (dish) {
                        dish.dicon = imgUrl + dish.dicon;
                    });
                    res.json(dishes);
                });
            }else{
                res.json([]);
            }
        } else {
            Dish.find(req.query, function (err, dishes) {
                res.json(dishes);
            });
        }
    }
    if(req.query.mid){
        req.session.mid = req.query.mid;
        res.redirect("../merchant.html");
    }
};